package com.dcjt.firehotcarpad.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aries.library.fast.module.fragment.FastTitleRefreshLoadFragment
import com.aries.library.fast.util.FastUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusEditText
import com.aries.ui.view.title.TitleBarView
import com.aries.ui.widget.progress.UIProgressView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.adapter.DisasterListAdapter
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.DisasterInfoEntity
import com.dcjt.firehotcarpad.model.DisasterListViewModel
import com.dcjt.firehotcarpad.moudle.ScreeningActivity
import com.dcjt.firehotcarpad.utils.InputSoftUtils

class DisasterListFragment : FastTitleRefreshLoadFragment<DisasterInfoEntity>() {

    private var type: Int = 1
    private lateinit var disasterListViewModel: DisasterListViewModel

    private lateinit var mAdapter: DisasterListAdapter
    private var dialog: UIProgressView? = null
    private var size: Int = 10
    private lateinit var ret_Search :RadiusEditText
    private var page: Int = 1

    var params = HashMap<String, Any>()

    companion object {
        fun newInstance(type: Int): DisasterListFragment {
            val fragment = DisasterListFragment()
            val bundle = Bundle()
            bundle.putInt("type", type)
            fragment.setArguments(bundle)
            return fragment
        }
    }

    @SuppressLint("ResourceAsColor")
    override fun setTitleBar(titleBar: TitleBarView?) {
//        titleBar?.visibility = View.GONE
        titleBar?.setLeftTextDrawable(R.drawable.icon_back)
        titleBar?.setTitleMainText("灾情列表")
            ?.setBackgroundColor(this.resources.getColor(R.color.bluebg))
        titleBar?.setTitleMainTextColor(this.resources.getColor(R.color.write))
            ?.setTitleMainTextSize(this.resources.getDimension(R.dimen.main_size))
            ?.setOnLeftTextClickListener { mContext.finish() }
//            ?.setRightTextDrawable(R.drawable.screen)
//            ?.setOnRightTextClickListener {
//                FastUtil.startActivity(mContext, ScreeningActivity::class.java)
//            }
//        titleBar?.height = 90
        val searchView =
            LayoutInflater.from(mContext).inflate(R.layout.layout_serach_item, null) as View
////        titleBar?.addRightAction(titleBar?.ViewAction(LayoutInflater.from(this).inflate(R.layout.layout_serach_item, null)),0)
        titleBar?.addRightAction(titleBar?.ViewAction(searchView), 0)
        ret_Search = searchView.findViewById<RadiusEditText>(R.id.ret_search)
        var search_del = searchView.findViewById<ImageView>(R.id.iv_search_del)
        var iv_screen = searchView.findViewById<ImageView>(R.id.iv_screen)
        iv_screen.setOnClickListener {
            val intent = Intent(mContext, ScreeningActivity::class.java)
            this.startActivityForResult(intent, ApiPath.RESULT_CODE_SELECT)
        }
        ret_Search.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length!! > 0) {
                    search_del.visibility = View.VISIBLE
                } else {
                    search_del.visibility = View.INVISIBLE
                }
            }

        })
        ret_Search.setOnKeyListener { v, keyCode, event ->
            //这里注意要作判断处理，ActionDown、ActionUp都会回调到这里，不作处理的话就会调用两次
            if (KeyEvent.KEYCODE_SEARCH == keyCode && KeyEvent.ACTION_DOWN == event.getAction() && ret_Search.text.trim().length > 0) {
                //处理事件
                params["keyword"] = ret_Search.text.trim().toString()
                setParamsKeyword()
                loadData(0)
                return@setOnKeyListener true;
            } else if(KeyEvent.KEYCODE_DEL == keyCode && ret_Search.text.trim().toString().length == 0){
                params["keyword"] = ""
                setParamsKeyword()
                loadData(0)
                return@setOnKeyListener true;
            }
            return@setOnKeyListener false
        }

        ret_Search.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //隐藏键盘
                InputSoftUtils.hideInput(mContext, ret_Search)
                params["keyword"] = ret_Search.text.trim().toString()
                setParamsKeyword()
                loadData(0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }


        search_del.setOnClickListener {
            ret_Search.text.clear()
            params["keyword"] = ""
            setParamsKeyword()
            loadData(0)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == ApiPath.RESULT_CODE_SELECT && resultCode == ApiPath.RESULT_OK) {

            if (data != null) {
                params["ajdj"] = data.getStringExtra("ajdj")
                params["ajdjdm"] = data.getStringExtra("ajdjdm")
                params["ajlx"] = data.getStringExtra("ajlx")
                params["ajlxdm"] = data.getStringExtra("ajlxdm")
                params["startime"] = data.getStringExtra("startime")
                params["endtime"] = data.getStringExtra("endtime")
                params["keyword"] = data.getStringExtra("keyword")
                ret_Search.setText(data.getStringExtra("keyword"))
                loadData(0)
            }
        }
        super.onActivityResult(requestCode, resultCode, data)

    }

    override fun getLayoutManager(): RecyclerView.LayoutManager {
        return GridLayoutManager(mContext, 2)
    }

    override fun getContentLayout(): Int = R.layout.fragment_layout_title_disaster_list

    @SuppressLint("UseRequireInsteadOfGet")
    override fun beforeInitView() {
        type = arguments!!.getInt("type")
        super.beforeInitView()
    }

    override fun initView(savedInstanceState: Bundle?) {
        params["size"] = 10
        params["current"] = 1
        params["keyword"] = ""
        setParamsKeyword()
        mAdapter?.openLoadAnimation(BaseQuickAdapter.SCALEIN)

        disasterListViewModel = ViewModelProviders.of(this).get(DisasterListViewModel::class.java)
        initLiveData()
        dialog = UIProgressView(mContext, UIProgressView.STYLE_WEI_BO).setMessage("加载中...")

        mEasyStatusView.loading()
        loadData(0)


    }

    private fun setParamsKeyword() {
        params["ajlx"] = ""
        params["ajlxdm"] = ""
        params["ajdj"] = ""
        params["ajdjdm"] = ""
    }

    override fun getAdapter() = DisasterListAdapter(null).apply {
        mAdapter = this
    }

    override fun loadData(page1: Int) {
        page = page1 + 1
        params["current"] = page
        disasterListViewModel.getDisasterList(params, mContext)
        dialog?.show()
    }

    override fun onItemClicked(
        adapter: BaseQuickAdapter<DisasterInfoEntity, BaseViewHolder>?,
        view: View?,
        position: Int
    ) {
        var bundle = Bundle()
//        bundle.putSerializable("disasterEntity", adapter?.getItem(position))
        bundle.putString("id", adapter?.getItem(position)?.id)
    }

    fun initLiveData() {
        disasterListViewModel.requestStatusLiveData.observe(
            this,
            androidx.lifecycle.Observer { data ->

                dialog?.dismiss()

                data?.let {
                    when (data.code) {
                        BaseEntity.ok -> {
                            mEasyStatusView.content()
                            mRefreshLayout.finishRefresh()
                            mAdapter?.loadMoreComplete()

                            if (it.data.records == null || it.data.records.isEmpty()) {
                                if (page == 1 && it.data.records.size == 0) {
                                    mEasyStatusView.empty()
                                } else {
                                    mAdapter?.loadMoreEnd()
                                }
                                return@Observer
                            }

                            if (mRefreshLayout.isRefreshing || page == 1) {
                                mAdapter?.setNewData(null)
                            }
                            mAdapter?.addData(it.data.records)
                            if (it.data.records.size < DEFAULT_PAGE_SIZE) {
                                mAdapter?.loadMoreEnd(true)
                            } else {

                            }
                        }
                        BaseEntity.err -> {
                            ToastUtil.show("网络请求失败", false)

                        }
                        else -> {
                            ToastUtil.show("服务器开小差了,请稍后再试!", false)
                        }
                    }

                }

            })
    }

}
